package com.rihel.servlets;

import com.rihel.dao.GoodsDao;
import com.rihel.model.Goods;
import com.rihel.util.CartHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CartServlet extends HttpServlet {
    private CartHelper cartHelper=null;
    private GoodsDao goodsDao = new GoodsDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("utf-8");

        //初始化
        if(request.getSession().getAttribute("cart")!=null){
            cartHelper = (CartHelper) request.getSession().getAttribute("cart");
        }else{
            cartHelper = new CartHelper();
            request.getSession().setAttribute("cart",cartHelper);
        }


        //判断动作
        String action = request.getParameter("action");

        if(action!=null){
            if(action.equals("add")){
                addGoods(request,response);
            }
        }
    }

    private void addGoods(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String goods_id = request.getParameter("goods_id");
        String redirect = request.getParameter("redirect");
        Goods goods = goodsDao.getGoodsById(Integer.parseInt(goods_id));
        cartHelper.addGoodsToCart(goods,1);
        request.getSession().setAttribute("cart",cartHelper);
        if(redirect!=null){
            request.getRequestDispatcher(redirect).forward(request,response);
        }else{
            request.getRequestDispatcher("cart.jsp").forward(request,response);
        }
        request.getSession().setAttribute("cart",cartHelper);
    }


}
